package org.wkg.lesson04;

public class Demo_401 {
    // 此处定义⼀个 int 类型的变量
    /*private static int count = 0;

    public static void main1(String[] args) throws InterruptedException {
        Object locker = new Object();
        Thread t1 = new Thread(() -> {
            // 对 count 变量进⾏⾃增 5w 次
            for (int i = 0; i < 50000; i++) {
                synchronized (locker) {
                    count++;
                }
            }
        });
        Thread t2 = new Thread(() -> {
            // 对 count 变量进⾏⾃增 5w 次
            for (int i = 0; i < 50000; i++) {
                synchronized (locker) {
                    count++;
                }
            }
        });
        t1.start();
        t2.start();
        // 如果没有这俩 join, 肯定不⾏的. 线程还没自增完, 就开始打印了. 很可能打印出来的 cou
        t1.join();
        t2.join();
        // 预期结果应该是 10w
        System.out.println("count: " + count);
    }*/


    public static void main(String[] args) throws InterruptedException {
        Counter401 counter = new Counter401();

        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.increase();
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.increase();
            }
        });

        t1.start();
        t2.start();
        t1.join();
        t2.join();

        System.out.println("count : "+counter.count);
    }


}

class Counter401 {
    public int count = 0;

    public synchronized void increase() {
        count++;
    }


}


